package com.nj.dms.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.nj.dms.bean.Essay;
import com.nj.dms.bean.PageBean;
import com.nj.dms.dao.EssayDao;
import com.nj.dms.dao.UserDao;
import com.nj.dms.dao.impl.EssayDaoImpl;
import com.nj.dms.dao.impl.UserDaoImpl;

/**
 * 查询我的文章并以列表的方式显示到页面
 */
@WebServlet("/MyEssayList")
public class MyEssayList extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 获取用户名
		String userName = (String) request.getSession().getAttribute("userName");

		// 获取页面传递过来的要显示的当前页的值
		String scurPage = request.getParameter("curPage");

		// 设置每页显示的最大记录数
		int maxSize = 13;

		if (userName != null) {

			EssayDao essayDao = new EssayDaoImpl();

			// curPage表示要显示的页[当前页],默认值是1
			int curPage = 1;
			if (scurPage != null) {
				curPage = Integer.parseInt(scurPage.trim());
			}

			// 计算显示记录的开始位置 开始位置 = (要显示的页 - 1) * 每页显示的最大数量
			Integer beginIndex = (curPage - 1) * maxSize;

			int recordNums = essayDao.countEssaysByUser(userName);

			PageBean pageBean = new PageBean();

			pageBean.init(curPage, maxSize, recordNums);

			List<Essay> essayList = essayDao.findAllEssayByUserByPage(userName, beginIndex, maxSize);

			request.setAttribute("pageBean", pageBean);
			request.setAttribute("myEssayList", essayList);

			// 执行服务器跳转，不改变浏览器地址，将请求传递下去
			request.getRequestDispatcher("document/my-essay-list.jsp").forward(request, response);

		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
